package com.jmpt.fangbohui.ui.personalcenter;

import java.util.List;

import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.graphics.Paint;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.provider.SyncStateContract.Constants;
import android.text.TextUtils;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnKeyListener;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.TextView;
import android.widget.Toast;

import com.google.gson.Gson;
import com.jmpt.fangbohui.R;
import com.jmpt.fangbohui.bean.LoginBean;
import com.jmpt.fangbohui.bean.NewLoginBean;
import com.jmpt.fangbohui.dao.LoginSQLiteOperator;
import com.jmpt.fangbohui.http.ApiRequest;
import com.jmpt.fangbohui.http.JsonHttpHandler;
import com.jmpt.fangbohui.ui.base.BaseActivity;
import com.jmpt.fangbohui.utils.DebugLog;
import com.jmpt.fangbohui.utils.SharePerfencesUtils;
import com.jmpt.fangbohui.utils.ToastHelper;
import com.lidroid.xutils.HttpUtils;
import com.lidroid.xutils.exception.HttpException;
import com.lidroid.xutils.http.RequestParams;
import com.lidroid.xutils.http.ResponseInfo;
import com.lidroid.xutils.http.callback.RequestCallBack;
import com.lidroid.xutils.http.client.HttpRequest;
import com.loopj.android.http.RequestHandle;
/**
 * 
 *
 * @package com.jmpt.fangbohui.ui.personalcenter
 * @author cangJie
 * @description 用户登录界面
 *
 */
public class LoginActivity extends BaseActivity implements OnClickListener {

	private EditText et_activity_my_login_username;
	private EditText et_activity_my_login_password;
	private CheckBox cb_activity_my_login_remenber;
	private TextView tv_activity_my_register;
	private Button bt_activity_my_login;
	private ImageButton btn_base_head_left_imgbutton;
	private String username;
	private String password;
	private SharedPreferences sharedPreferences; 
	private final static int SUCCESS = 1;
	private final static int ERROR = 2;
	private final static int FAILURE = 3;
	private static final String TAG = "LoginActivity";
	public static final String FILE_NAME="saveUserNamePwd";
	private Handler handler = new Handler(){
		public void handleMessage(android.os.Message msg) {
			switch(msg.what){
			case SUCCESS :
				
				//保存密码
				if(cb_activity_my_login_remenber.isChecked()){
					SharePerfencesUtils.setUserCache(LoginActivity.this, username, password);
				}else{
					SharePerfencesUtils.setUserCache(LoginActivity.this, "", "");
				}
				
				LoginSQLiteOperator oper = new LoginSQLiteOperator(mContext);
				LoginBean login = (LoginBean) msg.obj;
				oper.addUser(login);
				finish();
				
			break;
			case ERROR :
				Toast.makeText(LoginActivity.this, "账号或密码错误", 0).show();
				break;
			case FAILURE :
				Toast.makeText(LoginActivity.this, "网络连接出错", 0).show();
				break;
			}
		};
	};
	private Button bt_activity_broker_login;
	
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		initView();
		initEvent();
	}

	private void initEvent() {
		bt_activity_my_login.setOnClickListener(this);
		bt_activity_broker_login.setOnClickListener(this);
		tv_activity_my_register.setOnClickListener(this);
		btn_base_head_left_imgbutton.setOnClickListener(this);
	}

	private void initView() {
		setContentView(R.layout.activity_my_login);
		et_activity_my_login_username = (EditText) findViewById(R.id.et_activity_my_login_username);
		et_activity_my_login_password = (EditText) findViewById(R.id.et_activity_my_login_password);
		cb_activity_my_login_remenber = (CheckBox) findViewById(R.id.cb_activity_my_login_remenber);
		tv_activity_my_register = (TextView) findViewById(R.id.tv_activity_my_register);
		bt_activity_my_login = (Button) findViewById(R.id.bt_activity_my_login);
		bt_activity_broker_login = (Button) findViewById(R.id.bt_activity_broker_login);
		
		//下划线
		tv_activity_my_register.getPaint().setFlags(Paint.UNDERLINE_TEXT_FLAG);
		
		btn_base_head_left_imgbutton = (ImageButton) findViewById(R.id.btn_base_head_left_imgbutton);
		TextView tv_base_head_title = (TextView) findViewById(R.id.tv_base_head_title);
		Button btn_base_head_right_button = (Button) findViewById(R.id.btn_base_head_right_button);
		tv_base_head_title.setText("用户登录");
		btn_base_head_left_imgbutton.setVisibility(View.VISIBLE);
		btn_base_head_right_button.setVisibility(View.GONE);
		
		List<String> userCache = SharePerfencesUtils.getUserCache(this);
		et_activity_my_login_username.setText(userCache.get(0));
		et_activity_my_login_password.setText(userCache.get(1));
		
	}

	@Override
	public void onClick(View v) {
		switch(v.getId()){
		case R.id.bt_activity_my_login:
			username = et_activity_my_login_username.getText().toString().trim();
			password = et_activity_my_login_password.getText().toString().trim();
				
			if(TextUtils.isEmpty(username)){
				ToastHelper.ShowToast("账户不能为空", this);
				return;
			}
			if(TextUtils.isEmpty(password)){
				ToastHelper.ShowToast("密码不能为空", this);
				return;
			}
			
			//第一个是保存的文件的名称，第二个参数是保存的模式（是否只被本应用使用）
			sharedPreferences =
			getSharedPreferences(FILE_NAME, Context.MODE_PRIVATE);
			Editor editor = sharedPreferences.edit();
			//添加要保存的数据
			editor.putString("username", username );
			if (cb_activity_my_login_remenber.isChecked()) {// 自动登录
				
				editor.putString("password", password);
			}
			else
			{
				editor.putString("password", "");
			}
			//确认保存
			editor.commit();
			
			//TODO
//			JsonHttpHandler jHandler = new JsonHttpHandler(mContext);
//			RequestHandle request = ApiRequest.userLogin(mContext, username, password, jHandler);
//			System.out.println(request);
			
			
			
				checkUser(username,password);
		break;
		case R.id.btn_base_head_left_imgbutton:
			finish();
		break;
		case R.id.tv_activity_my_register:
			Log.d(TAG, "进入注册页面");
			Intent userRegister = new Intent(this,UserRegisterActivity.class);
			startActivity(userRegister);
		break;
		case R.id.bt_activity_broker_login:
			Intent intent = new Intent(this,BrokerLoginActivity.class);
			startActivity(intent);
			finish();
		break;
		
		}
	}
	public void checkUser(String username,String password){
		HttpUtils utils = new HttpUtils();
		String url = com.jmpt.fangbohui.Constants.URL.USERLOGINURL;
		RequestParams params = new RequestParams();
		params.addBodyParameter("phone", username);
		params.addBodyParameter("password", password);
		utils.send(HttpRequest.HttpMethod.POST, url, params, new RequestCallBack<String>() {
			Message msg = null;
			@Override
			public void onSuccess(ResponseInfo<String> responseInfo) {
				LoginBean webLoginBean = null;
				String result = responseInfo.result;
				DebugLog.i("user"+result);
				Gson gson = new Gson();
				webLoginBean = gson.fromJson(result, LoginBean.class);
				if(webLoginBean.done.equals("true")){
					webLoginBean.getRetval().setType(1);
					System.out.println(webLoginBean);
					if(webLoginBean.getRetval().getFlag().equals("error")){
						msg = Message.obtain();
						msg.what = ERROR;
						handler.sendMessage(msg);
					}else{
						msg = Message.obtain();
						msg.what = SUCCESS;
						msg.obj = webLoginBean;
						handler.sendMessage(msg);
					}
				}else{
					msg = Message.obtain();
					msg.what = ERROR;
					handler.sendMessage(msg);
				}
			}

			@Override
			public void onFailure(HttpException error, String msg) {
				this.msg = Message.obtain();
				this.msg.what = FAILURE;
				handler.sendMessage(this.msg);
			}
		});

	}




}
